<template>
  <div>
    <div v-show="$route.name == 'task-list'">
      <!-- 面包屑导航区域 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>任务管理记录</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 卡片视图区域 -->
      <el-card>
        <div style="margin-bottom: 20px;">任务管理记录</div>
        <!-- 搜索与添加区域 -->
        <el-row v-if="auths.indexOf('publish-task') !== -1">
          <el-col :span="24">
            <el-button type="success" @click="addTask">发布任务</el-button>
          </el-col>
        </el-row>
        <el-row class="query">
          <el-col :span="24">
            <el-select v-model="search.department_id" popper-class="dropdownbox" placeholder="请选择部门" v-if="chooseDepartment" class="query-search">
              <el-option v-for="item in departmentList" :label="item.name"
                :value="item.id" :key="item.id">
                <span style="float: left">{{ item.name }}</span>
              </el-option>
            </el-select>
            <el-select v-model="search.project_id" popper-class="dropdownbox" placeholder="请选择项目" clearable class="query-search" style="margin-left: 5px;width:200px;">
              <el-option v-for="item in projectList" :label="item.project_name"
                :value="item.id" :key="item.id">
                <span style="float: left">{{ item.project_name }}</span>
              </el-option>
            </el-select>
            <el-select v-model="search.task_status" popper-class="dropdownbox" placeholder="请选择任务状态" clearable class="query-search" style="margin-left: 5px;width:200px;">
              <el-option v-for="item in statusList" :label="item.name"
                :value="item.value" :key="item.value">
                <span style="float: left">{{ item.name }}</span>
              </el-option>
            </el-select>
            <el-select v-model="search.task_user_id" popper-class="dropdownbox" class="form-item" clearable placeholder="请选择负责人" style="margin-left: 5px;width:200px;" v-if="auths.indexOf('show-director') !== -1">
              <el-option v-for="item in userList" :label="item.name"
                :value="item.id" :key="item.id">
                <span style="float: left">{{ item.name }}</span>
              </el-option>
            </el-select>
            <el-button class="query-button" @click="reset" style="margin-left: 5px;">重置</el-button>
            <el-button type="primary" @click="searchData" class="query-button" style="margin-left: 5px;">搜索</el-button>
          </el-col>
        </el-row>
        <el-table
          border
          :loading="loading"
          :data="taskData"
          style="margin-top: 10px;">
          <el-table-column type="index" :index="indexMethod" width="50" align="center"></el-table-column>
          <el-table-column label="项目" prop="project_name" min-width="115" align="center"></el-table-column>
          <el-table-column label="任务名称" prop="task_name" min-width="135" align="center"></el-table-column>
          <el-table-column label="预计完成时间" prop="estimated_date" min-width="100" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.estimated_date ? new Date(scope.row.estimated_date).toLocaleDateString().split('/').join('-'): '' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="开发状态" prop="dev_status" min-width="90" align="center">
            <template slot-scope="scope">
              <el-button type="text" v-if="scope.row.dev_status === 1" style="color: #409EFF;" @click="changeStatus(scope.row)">未开始</el-button>
              <el-button type="text" v-else-if="scope.row.dev_status === 2" style="color: #E6A23C;" @click="changeStatus(scope.row)">开发中</el-button>
              <el-button type="text" v-else-if="scope.row.dev_status === 3" style="color: #9470dc;" @click="changeStatus(scope.row)">暂缓</el-button>
              <el-button type="text" v-else-if="scope.row.dev_status === 4" style="color: #67C23A;" @click="changeStatus(scope.row)">已完成</el-button>
            </template>
          </el-table-column>
          <el-table-column label="需要检查" prop="is_check" min-width="75" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.is_check === 1">是</span>
              <span v-else>否</span>
            </template>
          </el-table-column>
          <el-table-column label="检查状态" prop="check_status" min-width="90" align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.dev_status !== 3 && scope.row.is_check">
                <el-button type="text" v-if="scope.row.check_status === 1" style="color: #E6A23C;" @click="changeStatus(scope.row)">待检查</el-button>
                <el-button type="text" v-else-if="scope.row.check_status === 2" style="color: #F56C6C;" @click="changeStatus(scope.row)">已驳回</el-button>
                <el-button type="text" v-else-if="scope.row.check_status === 3" style="color: #67C23A;" @click="changeStatus(scope.row)">已通过</el-button>
              </div>
              <el-button type="text" v-else-if="!scope.row.is_check && scope.row.dev_status === 4" style="color: #67C23A;" @click="changeStatus(scope.row)">已完成</el-button>
            </template>
          </el-table-column>
          <el-table-column label="负责人" prop="task_user" min-width="90" align="center" v-if="auths.indexOf('show-director') !== -1">
            <template slot-scope="scope">
              <el-button type="text" @click="clickUser(scope.row.task_user_id)">{{scope.row.task_user}}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="完成时间" prop="complete_date" min-width="100" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.complete_date ? new Date(scope.row.complete_date).toLocaleDateString().split('/').join('-'): '' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="任务描述" prop="desc" min-width="200" align="center"></el-table-column>
          <el-table-column label="权重" min-width="190" align="center" v-if="auths.indexOf('show-weight') !== -1">
            <template slot-scope="scope">
              <div v-if="scope.row.new_status === 1">
                <el-button size="mini" :disabled="scope.$index === 0 && pager.currPage === 1" @click="clickMove(scope.$index, scope.row, 'up')"><i
                  class="el-icon-arrow-up"></i></el-button>
                <el-button size="mini" :disabled="scope.row.last" @click="clickMove(scope.$index, scope.row, 'down')"><i class="el-icon-arrow-down"></i></el-button>
                <el-button size="mini" :disabled="scope.$index === 0 && pager.currPage === 1" @click="clickMove(scope.$index, scope.row, 'top')">置顶</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="160" align="center" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="warning" @click="clickButton(scope.row.id, 2)" style="margin-right: 5px;">编辑</el-button>
              <el-button size="mini" type="danger" @click="clickButton(scope.row.id, 3)" v-if="auths.indexOf('delete-task') !== -1">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pager.currPage"
          :page-sizes="[1, 3, 5, 10]"
          :page-size="pager.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pager.totalCount">
        </el-pagination>
      </el-card>
      <el-dialog
      title="修改状态"
      :visible.sync="statusOpen"
      :before-close="cancel"
      width="550px">
        <el-form :model="updateStatus" :rules="rules" ref="task" label-width="120px" class="demo-saveForm">
          <el-row>
            <el-col :span="24">
              <el-form-item label="开发状态" prop="dev_status">
                <el-radio-group v-model="updateStatus.dev_status" :disabled="auths.indexOf('dev-all-status') !== -1 || (userId * 1 === updateStatus.task_user_id && auths.indexOf('dev-status') !== -1) ? false: true">
                  <el-radio :label="1">未开始</el-radio>
                  <el-radio :label="2">开发中</el-radio>
                  <el-radio :label="3">暂缓</el-radio>
                  <el-radio :label="4">已完成</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="需要检查" prop="is_check">
                <el-radio-group v-model="updateStatus.is_check" :disabled="auths.indexOf('choose-checkable') !== -1 ? false: true">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" v-if="updateStatus.is_check && updateStatus.check_status !== 0 && oldCheck !== 2">
              <el-form-item label="检查状态" prop="check_status">
                <el-radio-group v-model="updateStatus.check_status" :disabled="auths.indexOf('check-status') !== -1 ? false: true">
                  <el-radio :label="1">待检查</el-radio>
                  <el-radio :label="2">已驳回</el-radio>
                  <el-radio :label="3">已通过</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="ok">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <div>
      <router-view />
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      auths: [],
      userId: '',
      loading: false,
      pager: {
        currPage: 1,
        pageSize: 10,
        totalPage: 1,
        totalCount: 0
      },
      taskData: [],
      search: {
        project_id: '',
        task_status: '',
        task_user_id: '',
        department_id: ''
      },
      projectList: [],
      statusList: [
        {
          value: 1,
          name: '未开始'
        },
        {
          value: 2,
          name: '开发中'
        },
        {
          value: 3,
          name: '检查中'
        },
        {
          value: 4,
          name: '暂缓'
        },
        {
          value: 5,
          name: '已完成'
        },
        
      ],
      userList: [],
      // 上一列表
      lastList: [],
      // 下一列表
      nextList: [],
      // 修改状态
      statusOpen: false,
      updateStatus: {},
      rules: {
        dev_status: [{ required: true, message: '请选择开发状态', trigger: 'change' }],
        is_check: [{ required: true, message: '请选择是否检查', trigger: 'change' }],
        check_status: [{ required: true, message: '请选择检查状态', trigger: 'change' }]
      },
      devAble: true,
      checkAble: true,
      oldDev: '',
      oldCheck: '',
      // 可用的部门ID
      departmentId: [],
      chooseDepartment: false,
      departmentList: []
    }
  },
  watch: {
    $route(now, old) {
      if (old.name === 'task-detail' || old.name === 'task-save' || old.name === 'task-update') {
        this.getTaskList()
      }
    },
    'updateStatus.is_check': {
      handler: function(val, oldval) {
        if (val === 0 && oldval > -1) {
          this.updateStatus.check_status = 0
        } else if (val && this.updateStatus.dev_status === 4 && oldval > -1) {
          this.updateStatus.check_status = 1
        }
      }
    },
    'updateStatus.check_status': {
      handler: function(val, oldval) {
        // 数据有变 且 测试状态主动变化
        if (oldval > -1 && this.checkAble) {
          // 若检查状态不变
          if (val === this.oldCheck && this.updateStatus.dev_status !== this.oldDev) {
            this.devAble = false // 开发状态被动变化
            this.updateStatus.dev_status = this.oldDev
          // 检查状态修改为已驳回
          } else if (val === 2 && this.updateStatus.dev_status !== 2) {
            this.devAble = false // 开发状态被动变化
            this.updateStatus.dev_status = 2
          // 检查状态修改为已通过
          } else if (this.updateStatus.dev_status !== 4 && this.updateStatus.is_check) {
            this.devAble = false // 开发状态被动变化
            this.updateStatus.dev_status = 4
          }
        // 测试状态被动变化（改为主动）
        } else if (!this.checkAble) {
          this.checkAble = true
        }
      }
    },
    'updateStatus.dev_status': {
      handler: function(val, oldval) {
        // 数据有变 且 是开发状态主动变化
        if (oldval > -1 && this.devAble) {
          // 若开发状态不变
          if (val === this.oldDev && this.updateStatus.check_status !== this.oldCheck) {
            this.checkAble = false // 测试状态被动变化
            this.updateStatus.check_status = this.oldCheck
          // 若开发状态改为完成 检查状态改为待检查
          } else if (val === 4 && this.updateStatus.check_status !== 1 && this.updateStatus.is_check) {
            this.checkAble = false // 测试状态被动变化
            this.updateStatus.check_status = 1
          // 其余 检查状态改为0
          } else if (this.updateStatus.check_status !== 0) {
            this.checkAble = false // 测试状态被动变化
            this.updateStatus.check_status = 0
          }
        // 开发状态被动变化（改为主动）
        } else if (!this.devAble) {
          this.devAble = true
        }
      }
    },
    'search.department_id': {
      handler: function(val, oldval) {
        if (val) {
          this.getDevUser([val])
          this.getProjectList([val])
          this.search.task_user_id = ''
        } else {
          this.getDevUser(this.departmentId)
          this.getProjectList(this.departmentId)
        }
      }
    }
  },
  async mounted() {
    // 获取用户信息 可用部门ids
    await this.getUserInfo()
    // 显示负责人选择
    if (this.auths.indexOf("show-director") !== -1) {
      // 获取负责人选项
      await this.getDevUser(this.departmentId)
    }
    // 是否可以选择部门
    if (this.auths.indexOf('change_department') !== -1) {
      this.chooseDepartment = true
    }
    // 获取负责人id
    if (this.$route.params.task_user_id) {
      this.search.task_user_id = this.$route.params.task_user_id.toString()
    }
    // 获取任务状态查询
    if (this.$route.params.task_status) {
      this.search.task_status = this.$route.params.task_status
    }
    // 获取项目列表
    await this.getProjectList(this.departmentId)
    // 获取任务
    await this.getTaskList()
  },
  created() {
    // 是否可以展示用户列表
    this.auths = JSON.parse(localStorage.task_auths)
  },
  methods: {
    // 获取用户信息
    async getUserInfo() {
      this.auths = JSON.parse(localStorage.task_auths)
      this.userId = localStorage.task_user
      const { data: result } = await this.$http.get('/user/' + this.userId)
      this.departmentList = result.data.department
      result.data.department.forEach(element => {
        this.departmentId.push(element.id)
      })
    },
    addTask() {
      this.$router.push({ 'name': 'task-save' })
    },
    async getDevUser(val) {
      const params = {
        page: 1,
        pageSize: 100000,
        department_id: val
      }
      const { data: result } = await this.$http.get('/user', { params: params })
      if (result.status !== 200) {
        return this.$message.error(result.msg)
      }
      this.userList = result.data.map(item => {
        return {
          id: item.id.toString(),
          name: item.truename
        }
      })
    },
    async getTaskList(type = '', pager = '') {
      this.loading = true
      var params = {}
      if (type) {
        params = {
          page: pager.currPage,
          pageSize: pager.pageSize,
          departmentId: this.search.department_id ? [this.search.department_id] : this.departmentId
        }
        // 纯开发
        if (this.auths.indexOf('task-list-user') !== -1 && this.auths.indexOf('task-list-checkable') === -1) {
          params.task_user_id = this.userId
        // 开发且检查
        } else if (this.auths.indexOf('task-list-user') !== -1 && this.auths.indexOf('task-list-checkable') !== -1) {
          params.check_user = this.userId
          if (this.search.task_user_id !== '') {
            params.task_user_id = this.search.task_user_id
          }
          params.is_check = 1
        // 纯检查
        } else if (this.auths.indexOf('task-list-checkable') !== -1) {
          if (this.search.task_user_id !== '') {
            params.task_user_id = this.search.task_user_id
          }
          params.is_check = 1
        } else if (this.search.task_user_id !== '') {
          params.task_user_id = this.search.task_user_id
        }
        if (this.search.project_id !== '') {
          params.project_id = this.search.project_id
        }
        if (this.search.task_status !== '') {
          params.task_status = this.search.task_status
        }
        const { data: result } = await this.$http.get('/task', { params: params })
        if (result.status !== 200) {
          this.$message.error(result.msg)
          return false
        }
        if (type === 'up') {
          this.lastList = result.data
        } else if (type === 'down') {
          this.nextList = result.data
        }
      } else {
        params = {
          page: this.pager.currPage,
          pageSize: this.pager.pageSize,
          departmentId: this.search.department_id ? [this.search.department_id] : this.departmentId
        }
        // 纯开发
        if (this.auths.indexOf('task-list-user') !== -1 && this.auths.indexOf('task-list-checkable') === -1) {
          params.task_user_id = this.userId
        // 开发且检查
        } else if (this.auths.indexOf('task-list-user') !== -1 && this.auths.indexOf('task-list-checkable') !== -1) {
          params.check_user = this.userId
          if (this.search.task_user_id !== '') {
            params.task_user_id = this.search.task_user_id
          }
          params.is_check = 1
        // 纯检查
        } else if (this.auths.indexOf('task-list-checkable') !== -1) {
          if (this.search.task_user_id !== '') {
            params.task_user_id = this.search.task_user_id
          }
          params.is_check = 1
        } else if (this.search.task_user_id !== '') {
          params.task_user_id = this.search.task_user_id
        }
        if (this.search.project_id !== '') {
          params.project_id = this.search.project_id
        }
        if (this.search.task_status !== '') {
          params.task_status = this.search.task_status
        }
        const { data: result } = await this.$http.get('/task', { params: params })
        if (result.status !== 200) {
          this.loading = false
          this.taskData = '暂无数据'
          return this.$message.error(result.msg)
        }
        this.loading = false
        this.taskData = result.data
        this.pager = result.pager
      }
    },
    clickButton(id, type) {
      if (type === 1) {
        this.$router.push({
          name: 'task-detail',
          params: { id: id }
        })
      } else if (type === 2) {
        this.$router.push({
          name: 'task-update',
          params: { id: id }
        })
      } else if (type === 3) {
        this.deleteTask(id)
      }
      // else {
      //   this.dialogVisible = true
      //   this.taskUpdate = id
      // }
    },
    async deleteTask(id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('删除该任务，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: result } = await this.$http.delete('/task/' + id)
      if (result.status !== 200) return this.$message.error(result.msg)
      this.getTaskList()
      this.$message.success('删除成功！')
    },
    handleSizeChange(pageSize) {
      this.pager.pageSize = pageSize
      this.getTaskList()
    },
    handleCurrentChange(currentPage) {
      this.pager.currPage = currentPage
      this.getTaskList()
    },
    async getProjectList(val) {
      const params = {
        page: 1,
        pageSize: 10000,
        userId: this.userId,
        departmentId: val
      }
      const { data: result } = await this.$http.get('/project', { params: params })
      if (result.status !== 200) {
        return this.$message.error(result.msg)
      }
      this.projectList = result.data
    },
    reset() {
      this.search = {
        project_id: '',
        task_user_id: '',
        task_status: '',
        department_id: ''
      }
      this.pager.currPage = 1
      this.getTaskList()
    },
    searchData() {
      this.pager.currPage = 1
      this.getTaskList()
    },
    indexMethod(index) {
      index = index + 1
      if (this.pager.currPage > 1) {
        index = index + (this.pager.currPage - 1) * this.pager.pageSize
      }
      return index
    },
    async clickMove(index, row, type) {
      var data = {}
      var lastTask = []
      var pager = {}
      var nextTask = []
      if (type === 'up') {
        // 第一个数据
        if (index === 0) {
          pager = {
            currPage: this.pager.currPage - 1,
            pageSize: this.pager.pageSize,
            totalCount: this.pager.totalCount,
            totalPage: this.pager.totalPage
          }
          await this.getTaskList(type, pager)
          lastTask = this.lastList.pop()
        } else {
          lastTask = this.taskData[index - 1]
        }
        data = {
          weight: lastTask.weight,
          type: type
        }
      } else if (type === 'down') {
        // 最后一个数据
        if (index === this.pager.pageSize - 1) {
          pager = {
            currPage: this.pager.currPage + 1,
            pageSize: this.pager.pageSize,
            totalCount: this.pager.totalCount,
            totalPage: this.pager.totalPage
          }
          await this.getTaskList(type, pager)
          nextTask = this.nextList[0]
        } else {
          nextTask = this.taskData[index + 1]
        }
        data = {
          weight: nextTask.weight,
          type: type
        }
      } else if (type === 'top') {
        // 第一个数据
        pager = {
          currPage: 1,
          pageSize: this.pager.pageSize,
          totalCount: this.pager.totalCount,
          totalPage: this.pager.totalPage
        }
        await this.getTaskList('up', pager)
        lastTask = this.lastList[0]
        data = {
          weight: lastTask.weight,
          type: 'up'
        }
      }
      const { data: result } = await this.$http.put('/task-weight/' + row.id, data)
      if (result.status !== 200) return this.$message.error(result.msg)
      this.getTaskList()
      this.$message.success('修改成功！')
    },
    clickUser(userId) {
      this.search.task_user_id = userId.toString()
      this.searchData()
    },
    // 修改状态
    changeStatus(row) {
      this.updateStatus = JSON.parse(JSON.stringify(row))
      this.oldDev = this.updateStatus.dev_status
      this.oldCheck = this.updateStatus.check_status
      this.statusOpen = true
    },
    // 取消
    cancel() {
      this.devAble = true
      this.checkAble = true
      this.oldDev = ''
      this.oldCheck = ''
      this.updateStatus = {}
      this.statusOpen = false
    },
    // 确认修改
    ok() {
      this.$refs.task.validate(async (valid) => {
        if (!valid) return
        let data = {
          dev_status: this.updateStatus.dev_status,
          is_check: this.updateStatus.is_check,
          check_status: this.updateStatus.check_status
        }
        const { data: result } = await this.$http.put('/task/' + this.updateStatus.id, { data: data })
        if (result.status !== 200) {
          return this.$message.error(result.msg)
        }
        this.cancel()
        this.$message.success('保存成功！')
        this.getTaskList()
      })
    }
  }
}
</script>

<style lang="less" scoped>
.query {
  margin-bottom: 10px;
  margin-top: 10px;
}
</style>
